package org.xp.judgeplatform.util;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@AllArgsConstructor
public class PasswordUtil {

    private final PasswordEncoder passwordEncoder;

    public String encodePassword(String rawPassword) {
        if (rawPassword == null || rawPassword.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        
        String encodedPassword = passwordEncoder.encode(rawPassword);
        log.debug("密码加密完成，长度: {} -> {}", rawPassword.length(), encodedPassword.length());
        return encodedPassword;
    }

    public boolean matches(String rawPassword, String encodedPassword) {
        if (rawPassword == null || encodedPassword == null) {
            log.warn("密码验证失败：参数为空");
            return false;
        }
        
        boolean matches = passwordEncoder.matches(rawPassword, encodedPassword);
        log.debug("密码验证: {}", matches ? "通过" : "失败");
        return matches;
    }

    public boolean isPasswordStrong(String password) {
        if (password == null || password.length() < 6) {
            return false;
        }
        return password.matches(".*\\d.*") && password.matches(".*[a-zA-Z].*");
    }
}